<?php
namespace app\admin\controller;

use app\BaseController;
use app\admin\model\User;
//use app\validate\User;
use think\exception\ValidateException;
require_once('../extend/JWT.php');

class Login extends BaseController
{

    //protected $middleware = \app\middleware\JWTAUTH::class;

    public function index()
    {
        //var_dump($this->request->method());die;
        if($this->request->method() == 'POST') {
            try{
                //var_dump($_POST['name']);die;
                validate(\app\validate\User::class)
                      ->scene('login')
                      ->check($this->request->param());
                $user=User::find(array(
                  'name' => $this->request->post('name'),
                  'password' => $this->request->post('password'),
                ));
                if($user->id){
                    header('Authorization:'.(new JWT(array(
                        'username' => $this->request->post('name'),
                        'types' => 'admin',
                        'userid' => 1,//$user->id,
                    )))->signatures());

                    return json_encode(array(
                        'status' => '100',
                        'message' => '你已登录成功',
                    ));
                }else {
                    return json_encode(array(
                        'status' => '104',
                        'message' => '你输入的用户名或密码有误',
                    ));
                }
            }catch(ValidateException $e){
                dump($e->getError());
            }
        }else{
            return json_encode(array(
              'status' => '101',
              'message' => '请求方法只允许post',
            ));
        }
    }

}
